# 分析
import os
import json
import requests
from SonicVisage import settings
from django.http import JsonResponse
from django.http import StreamingHttpResponse
from web.ai_tools.musics import music_2t58

music_line1 = music_2t58.Music2t58()


def StartChat(chat_message_url, params_data):
    # 开始对话
    chat_response = requests.get(chat_message_url, params=params_data, stream=True)
    for item in chat_response.iter_lines():
        item = item.decode('utf-8')
        yield item + "\n\n"

def UserStatusAnalysisAPI(request):
    if request.method == 'POST':
        try:
            uploaded_file = request.FILES['file']
            file_content = uploaded_file.read()
            
            # 发送文件到目标服务器
            target_url = settings.MyAi + 'api/TengXunYuanBao/file/update_file/'
            files = {'file': (uploaded_file.name, file_content)}
            response = requests.post(target_url, files=files)
            
            if response.status_code == 200:
                data = response.json()
                if data['code'] == 200:
                    with open(os.path.join(settings.STATIC_ROOT, "prompts", "UserStatusAnalysis.txt"), 'rb') as f:
                        read_data = f.read()
                        decoded_data = read_data.decode('utf-8')
                        target_url = settings.MyAi + 'api/TengXunYuanBao/JiChuBan/send_message/'
                        chat_id = requests.get(settings.MyAi + "api/TengXunYuanBao/JiChuBan/create_new_chat/").json()['id']
                        
                        # 定义对话url
                        chat_message_url = settings.MyAi + "api/TengXunYuanBao/JiChuBan/send_message/"
                        params_data = {
                            "message": decoded_data,
                            "chat_id": chat_id,
                            "model": "hunyuan_gpt_175B_0404",
                            "multimedia": json.dumps([ { "type": "image", "docType": "image", "url": data['resourceUrl'], "fileName": uploaded_file.name, "size": data['size'], "width": 0, "height": 0 } ], ensure_ascii=False)
                        }
                        chat_response = requests.get(chat_message_url, params=params_data, stream=True)
                        centent = ""
                        for item in chat_response.iter_lines():
                            item = item.decode('utf-8')
                            if item.startswith('data: '):
                                text = item.replace('data: ', '')
                                text = json.loads(text)
                                if text['type'] == "end":
                                    centent = json.loads(centent)
                                    centent['chat_id'] = chat_id
                                    break
                                else:
                                    centent += text['msg']
                            
                        # response = StreamingHttpResponse(StartChat(chat_message_url, params_data), content_type='text/event-stream')
                        # response.headers['Cache-Control'] = 'no-cache'
                        return JsonResponse({"code": 200, "data": centent})
            else:
                return JsonResponse({'status': 'error', 'message': '文件转发失败'}, status=500)
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=500)
    return JsonResponse({'status': 'error', 'message': '仅支持POST请求'}, status=400)




# 推荐api
def Detailed_Rigorous_StyleAPI(request):
    dict_text = json.loads(request.GET.get("prompt_json_text"))
    with open(os.path.join(settings.STATIC_ROOT, "prompts", "Detailed_Rigorous_Style.txt"), 'rb') as f:
        # 发送文件到目标服务器
        target_url = settings.MyAi + 'api/TengXunYuanBao/file/update_file/'
        files = {'file': ("Detailed_Rigorous_Style.txt", f.read())}
        response = requests.post(target_url, files=files).json()
        resourceUrl = response['resourceUrl']
        print(resourceUrl)

        # 定义对话url
        chat_message_url = settings.MyAi + "api/TengXunYuanBao/JiChuBan/send_message/"
        params_data = {
            "message": f"请你严格根据我的文件要求输出指定内容，下面是我的情绪报告: \n{dict_text}" ,
            "chat_id": dict_text['chat_id'],
            "model": "hunyuan_gpt_175B_0404",
            "multimedia": json.dumps([ { "type": "txt", "docType": "txt", "url": resourceUrl, "fileName": "Detailed_Rigorous_Style.txt", "size": response['size'], "width": 0, "height": 0 } ], ensure_ascii=False)
        }
        chat_response = requests.get(chat_message_url, params=params_data, stream=True)
        centent = ""
        for item in chat_response.iter_lines():
            item = item.decode('utf-8')
            if item.startswith('data: '):
                text = item.replace('data: ', '')
                text = json.loads(text)
                if text['type'] == "end":
                    centent = json.loads(centent)
                    centent['chat_id'] = dict_text['chat_id']
                    break
                else:
                    centent += text['msg']
            
        # response = StreamingHttpResponse(StartChat(chat_message_url, params_data), content_type='text/event-stream')
        # response.headers['Cache-Control'] = 'no-cache'
        return JsonResponse({"code": 200, "data": centent})


# 生成音乐
def get_music(request):
    if request.method == 'POST':
        try:
            music_list = json.loads(request.POST.get("music_list"))
            new_music = []
            # 遍历音乐列表
            for item in music_list:
                # 调用搜索音乐引擎
                search_music_list = music_line1.search_music(item['song_name'].replace("《", "").replace("》", ""))
                # 利用文本比对技术判断歌手是否存在于这首歌
                music_info = search_music_list['songs'][0]
                # 获取音乐ID
                music_id = music_info['id']

                # 获取播放链接
                play_url = music_line1.get_song_detail(music_id)
                # 分发给返回集合
                new_music.append(play_url)
                # 结束本次循环
                # break
            return JsonResponse({"code": 200, "data":new_music}, safe=False)
        except Exception as e:
            return JsonResponse({'status': 'error','message': str(e)}, status=500)
    return JsonResponse({'status': 'error','message': '仅支持POST请求'}, status=400)